import React, {useEffect, useState} from "react"
import {ArrowLeftOutlined} from "@ant-design/icons";
import {Button, Checkbox, Col, Divider, Form, Input, message, PageHeader, Row, Select} from "antd";
import {get, postJSON, putJSON} from "../../../shared/server"
import ToolTipsInput from "../../../shared/libs/tooltips-input";
import Tag from "antd/es/tag";
import CheckOutlined from "@ant-design/icons/lib/icons/CheckOutlined"
import brandColors from "../brandColors"

const {Option} = Select;

const priceInputStyle = {width: "200px"}


let timerId;
export default (props) => {
  const {history, match: {params}} = props;
  const isEdit = params.id && params.id >= 0;
  const [form] = Form.useForm();
  const [nameStatus, setNameStatus] = useState({});
  const [brandList, setBrandList] = useState([]);

  const layout = {
    labelCol: {span: 6},
    wrapperCol: {span: 16},
  };
  const tailLayout = {
    wrapperCol: {offset: 11},
  };

  useEffect(() => {
    if (isEdit) {
      get(`/management/product/${params.id}`).then(data => {
        const {name, briefCode, remarks, description, itemNo, prices,category} = data;
        form.setFieldsValue({
          itemNo,
          name,
          briefCode,
          remarks,
          description,
          category,
          prices,
        })
        setBrandList((prices || []).map(p => ({id: p.brandId, name: p.brandName})))
      })
    }
    get("/management/brand/list").then(response => {
      setBrandList(response || [])
    })
  }, []);

  const onFinish = values => {
    if (isEdit) {
      putJSON(`/management/product/${params.id}`, values).then(result => {
        if (result) {
          message.success("更新成功")
          history.push("/app/product")
          setNameStatus({})
        }
      })
    } else {
      postJSON('/management/product', values).then(result => {
        if (result) {
          message.success("添加成功")
          if (values.continue) {
            form.resetFields();
            setNameStatus({})
          } else {
            history.push("/app/product");
          }
        }
      })
    }
  };

  const onFinishFailed = errorInfo => {
    console.log('Failed:', errorInfo);
  };

  const debounceDelay = (fn, wait = 0, value) => {
    if (timerId) {
      clearTimeout(timerId);
      timerId = null;
    }
    timerId = setTimeout(() => {
      fn(value);
    }, wait);
  }

  const generateBriefCodeDelay = (value) => {
    get(`/management/common/py`, {word: value}).then(result => {
      if (result) {
        form.setFieldsValue({
          briefCode: result,
        })
      }
    })
  }

  const generateBriefCode = (event) => {
    debounceDelay(generateBriefCodeDelay, 500, event.target.value)
  }

  const checkDuplicateItemNo = ({postData, callback}) => {
    get(`/management/product/itemNo/checkDuplicate`, postData).then(result => {
      if (result === true) {
        callback(`项目编号${postData.itemNo}已经存在,请使用其它编号!`)
      }
      callback()
    }).finally(() => setNameStatus({}))
  }

  const nameValidate = (rule, value, callback) => {
    setNameStatus({validateStatus: 'validating'})
    let postData = {
      itemNo: value,
    };
    if (isEdit) {
      postData = {
        ...postData,
        id: params.id,
      }
    }
    debounceDelay(checkDuplicateItemNo, 500, {
      postData, callback
    });
  }

  const handleChange = (event) => {
    const value = event.target.value;
    value.replace(/[^\-?\d.]/g, '');
  }

  if (brandList.length === 0) return null;

  return (
    <div className="zr-panel">
      <div className="zr-panel-header">
        <PageHeader backIcon={<ArrowLeftOutlined/>}
                    onBack={() => window.history.back()} title={`${isEdit ? "编辑" : "新增"}项目`}
                    subTitle=""/>
      </div>
      <div className="zr-list-page-box body-bg body-border absolute">
        <div className="zr-table-box">
          <Form
            {...layout}
            style={{padding: 20}}
            form={form}
            name="basic"
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            initialValues={{
              prices: (brandList || []).map((item, index) => ({
                brandId: item.id,
                fieldKey: index,
                isListField: true,
                key: index,
                name: index
              }))
            }}
          >
            <Row>
              <Col span={12}>
                <Form.Item
                  label="项目编号"
                  name="itemNo"
                  hasFeedback
                  {...nameStatus}
                  validateFirst={true}
                  rules={[
                    {required: true, message: "项目编号必须填写"},
                    {pattern: /^[A-Za-z0-9]+$/, message: "编号只能输入数字和字母"},
                    {validator: nameValidate}
                  ]}
                >
                  <ToolTipsInput
                    title="项目编号,可输入最多20位数字和字母"
                    id="_itemNo"
                    placeholder="请输入项目编号"
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="项目分类"
                  name="category"
                  validateFirst={true}
                  rules={[
                    {min: 2, message: '分类长度不得少于2'},
                    {max: 12, message: '分类长度不得多于12'}
                  ]}
                >
                  <ToolTipsInput
                    title="项目分类,可输入2-12位分类名称"
                    id="_category"
                    placeholder="请输入项目分类"
                  />
                </Form.Item>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <Form.Item
                  label="项目名称"
                  name="name"
                  validateFirst={true}
                  rules={[
                    {required: true, message: "项目名称必须填写"},
                  ]}
                >
                  <ToolTipsInput
                    title="项目名称,最大50个字符"
                    id="_name"
                    placeholder="请输入项目名称"
                    onChange={generateBriefCode}
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="项目简码"
                  name="briefCode"
                  validateFirst={true}
                  rules={[
                    {required: true, message: "项目简码必须填写"},
                    {pattern: /^[A-Za-z0-9]+$/, message: "简码只能输入数字和字母"},
                  ]}
                >
                  <ToolTipsInput title="项目简码,一般为项目名称拼音首字母" id="_briefCode" placeholder="请输入简码"/>
                </Form.Item>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <Form.Item
                  label="说明"
                  name="description"
                  rules={[{required: false, message: '备注!'}]}
                >
                  <Input.TextArea rows={4} placeholder={'项目描述,500字以内(业务员可见)'}/>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="备注"
                  name="remarks"
                  rules={[{required: false, message: '备注!'}]}
                >
                  <Input.TextArea rows={4} placeholder={'项目备注,500字以内(仅管理员可见)'}/>
                </Form.Item>
              </Col>
            </Row>

            <Form.List name="prices">
              {(fields) => {
                return (
                  <div>
                    {fields.map((field, index) => {
                        const brand = brandList[index]
                        return (
                          <div key={field.fieldKey}>
                            <Divider orientation="left">
                              <Tag color={brandColors[brand.id]} style={{fontSize: 14}}
                                   className={'large'}>{brand.name}价格</Tag>
                            </Divider>
                            <div key={`${field.fieldKey}`}>
                              <Row>
                                <Col span={12}>
                                  <Form.Item
                                    noStyle={true}
                                    {...field}
                                    name={[field.name, 'brandId']}
                                    fieldKey={[field.fieldKey, 'brandId']}
                                  >
                                    <Input type={"hidden"}/>
                                  </Form.Item>
                                </Col>
                              </Row>
                              <Row>
                                <Col span={12}>
                                  <Form.Item
                                    {...field}
                                    label="固定成本"
                                    name={[field.name, 'fixedCostPrice']}
                                    fieldKey={[field.fieldKey, 'fixedCostPrice']}
                                    validateFirst={true}
                                    rules={[
                                      {required: true, message: '成本价必须填写'},
                                      // /^\d+\.?\d*$/ 多位小数
                                      {pattern: /^\d+(\.\d{0,2})?$/, message: "请输入有效金额,最多两位小数(如:88.98)"}
                                    ]}
                                  >
                                    <ToolTipsInput
                                      isPrice={true}
                                      title="项目固定成本价,有效金额格式,最多两位小数"
                                      id="_fixedCostPrice"
                                      placeholder="固定成本价"
                                      onChange={handleChange}
                                      style={priceInputStyle}
                                    />
                                  </Form.Item>
                                </Col>
                                <Col span={12}>
                                  <Form.Item
                                    {...field}
                                    label="可变成本"
                                    name={[field.name, 'volatileCostPrice']}
                                    fieldKey={[field.fieldKey, 'volatileCostPrice']}
                                    validateFirst={true}
                                    rules={[{required: true, message: '可变成本价必须填写'},
                                      {pattern: /^\d+(\.\d{0,2})?$/, message: "请输入有效金额,最多两位小数(如:88.98)"}
                                    ]}
                                  >
                                    <ToolTipsInput
                                      isPrice={true}
                                      title="项目可变成本价,有效金额格式,最多两位小数"
                                      id="_volatileCostPrice"
                                      placeholder="可变成本价"
                                      style={priceInputStyle}
                                    />
                                  </Form.Item>
                                </Col>
                              </Row>
                              <Row>
                                <Col span={12}>
                                  <Form.Item
                                    {...field}
                                    label="其他成本"
                                    name={[field.name, 'otherCostPrice']}
                                    fieldKey={[field.fieldKey, 'otherCostPrice']}
                                    validateFirst={true}
                                    rules={[{required: true, message: '其他成本价必须填写'},
                                      {pattern: /^\d+(\.\d{0,2})?$/, message: "请输入有效金额,最多两位小数(如:88.98)"}
                                    ]}
                                  >
                                    <ToolTipsInput
                                      isPrice={true}
                                      title="项目其它成本价,有效金额格式,最多两位小数"
                                      id="_otherCostPrice"
                                      placeholder="其他成本价"
                                      style={priceInputStyle}
                                    />
                                  </Form.Item>
                                </Col>
                                <Col span={12}>
                                  <Form.Item
                                    {...field}
                                    label="市场价"
                                    name={[field.name, 'marketPrice']}
                                    fieldKey={[field.fieldKey, 'marketPrice']}
                                    validateFirst={true}
                                    rules={[{required: true, message: "市场价必须填写"},
                                      {pattern: /^\d+(\.\d{0,2})?$/, message: "请输入有效金额,最多两位小数(如:88.98)"}
                                    ]}
                                  >
                                    <ToolTipsInput
                                      isPrice={true}
                                      title="项目市场价(原价),有效金额格式,最多两位小数"
                                      id="_marketPrice"
                                      placeholder="市场价"
                                      style={priceInputStyle}
                                    />
                                  </Form.Item>
                                </Col>
                              </Row>
                            </div>
                          </div>
                        )
                      }
                    )}
                  </div>
                )
              }}
            </Form.List>
            {
              isEdit
                ? null
                : <Form.Item
                  {...tailLayout}
                  name="continue"
                  valuePropName="checked"
                  rules={[{required: false, message: '是否继续添加'}]}
                >
                  <Checkbox>连续添加</Checkbox>
                </Form.Item>
            }
            <Row>
              <Col span={24}>
                <Form.Item {...tailLayout} style={{marginTop: isEdit ? 10 : 0}}>
                  <Button type="primary" htmlType="submit"><CheckOutlined/>保存</Button>
                  <Button style={{marginLeft: 10}} onClick={() => window.history.back()}>
                    返回
                  </Button>
                </Form.Item>
              </Col>
            </Row>

          </Form>
        </div>
      </div>
    </div>
  )
}
